package com.hskn.hss.module.alarmcar.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hskn.hss.core.annotation.DataScope;
import com.hskn.hss.core.domain.BaseEntity;
import com.hskn.hss.core.page.TableDataInfo;
import com.hskn.hss.core.utils.LoginUtils;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.alarmHandleLog.domain.AlarmHandleLog;
import com.hskn.hss.module.alarmHandleLog.service.IAlarmHandleLogService;
import com.hskn.hss.module.alarmcar.entity.AlarmCar;
import com.hskn.hss.module.alarmcar.entity.AlarmCarCharts;
import com.hskn.hss.module.alarmcar.mapper.AlarmCarMapper;
import com.hskn.hss.module.alarmcar.service.IAlarmCarService;
import com.hskn.hss.module.alarmcar.vo.AlarmCarTableDetailVO;
import com.hskn.hss.module.carviolation.entity.CarViolation;
import com.hskn.hss.module.carviolation.mapper.CarViolationMapper;
import com.hskn.hss.module.depart.service.ISysDepartService;
import com.hskn.hss.module.messageFlowRecords.domain.MessageFlowRecords;
import com.hskn.hss.module.messageFlowRecords.service.IMessageFlowRecordsService;
import com.hskn.hss.module.tlcar.entity.TlCar;
import com.hskn.hss.module.tlcar.service.ITlCarService;
import com.hskn.hss.module.user.entity.User;
import com.hskn.hss.module.user.mapper.UserMapper;
import com.hskn.hss.utils.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hskn
 * @since 2021-05-21
 */
@Service
public class AlarmCarServiceImpl extends ServiceImpl<AlarmCarMapper, AlarmCar> implements IAlarmCarService {

    @Autowired
    IAlarmHandleLogService alarmHandleLogService;
    @Resource
    UserMapper userMapper;
    @Autowired
    ITlCarService carService;
    @Resource
    private AlarmCarMapper alarmCarMapper;
    @Resource
    private CarViolationMapper carViolationMapper;
    @Autowired
    private ISysDepartService departService;
    @Autowired
    public IMessageFlowRecordsService messageFlowRecordsService;
    @Autowired
    LocationUtils locationUtil;

    @Override
    @DataScope(deptAlias = "dep_id", userAlias = "deal_uid")
    public JSONObject mList(BaseEntity entity, JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        JSONObject json = new JSONObject();
        QueryWrapper<AlarmCar> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(AlarmCar::getCreateTime);
        if (entity.getParams().containsKey("dataScope")&&StringUtils.isNotEmpty(entity.getParams().get("dataScope"))) {
            queryWrapper.lambda().apply(entity.getParams().get("dataScope").toString());
        }
        String type = params.getString("type");
        if (StringUtils.isNotEmpty(type)) {
            queryWrapper.lambda().eq(AlarmCar::getCarTypeName, type);
        }
        String alarmCarId = params.getString("alarmCarId");
        if (StringUtils.isNotEmpty(alarmCarId)) {
            queryWrapper.lambda().eq(AlarmCar::getAlarmCarId, alarmCarId);
        }
        String carId = params.getString("carId");
        if (StringUtils.isNotEmpty(carId)) {
            queryWrapper.lambda().eq(AlarmCar::getCarId, carId);
        }
        String alarmTypeId = params.getString("alarmTypeId");
        if (StringUtils.isNotEmpty(alarmTypeId)) {
            queryWrapper.lambda().eq(AlarmCar::getAlarmTypeId, alarmTypeId);
        }
        String alarmTypeName = params.getString("alarmTypeName");
        if (StringUtils.isNotEmpty(alarmTypeName)) {
            queryWrapper.lambda().like(AlarmCar::getAlarmTypeName, alarmTypeName);
        }
        String startDate = params.getString("startDate");
        String endDate = params.getString("endDate");
        if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
            queryWrapper.lambda().between(AlarmCar::getAlarmTime, startDate + " 00:00:00", endDate + " 23:59:59");
        }
        Long page = StringUtils.isEmpty(params.getLong("page")) ? 1 : params.getLong("page");
        Long size = StringUtils.isEmpty(params.getLong("size")) ? 10 : params.getLong("size");
        Page<AlarmCar> alarmCarPage = new Page<>(page, size, true);
        IPage<AlarmCar> iPage = alarmCarMapper.selectPage(alarmCarPage, queryWrapper);
        Map<String, TlCar> carMap = carService.getCarMap(new QueryWrapper<>());
        List<AlarmCar> list = iPage.getRecords();

        for (AlarmCar alarmCar : list) {
            if (carMap.containsKey(alarmCar.getCarId())) {
                alarmCar.setCarHeadPortraitAlarm(carMap.get(alarmCar.getCarId()).getCarpicture());
            }
            MessageFlowRecords messageFlowRecords = new MessageFlowRecords();
            messageFlowRecords.setMessageId(alarmCar.getAlarmCarId());
            messageFlowRecords.setKind(1);
            messageFlowRecords.setSubjectType(2);
            messageFlowRecords.setUserId(uid);
            List<MessageFlowRecords> messageFlowRecordsList = messageFlowRecordsService.selectMessageFlowRecordsList(messageFlowRecords);
            if ((Objects.nonNull(messageFlowRecordsList) && messageFlowRecordsList.size() > 0) || alarmCar.getAlarmTime().compareTo(DateUtil.parseDateTime(AttributeUtils.timeCompletion(DateUtil.formatDate(new Date()), 's'))) < 0 ){
                alarmCar.setIsRead(1);
            } else {
                alarmCar.setIsRead(0);
            }
        }
        json.put("total", iPage.getTotal());
        json.put("size", iPage.getSize());
        json.put("pages", iPage.getPages());
        json.put("current", iPage.getCurrent());
        json.put("list", iPage.getRecords());
        return json;
    }

    @Override
    public JSONObject getAbnormal() {

        JSONObject result = new JSONObject();

        String day = DateUtil.formatDate(new Date());
        String startTime = AttributeUtils.timeCompletion(day, 's');
        String endTime = AttributeUtils.timeCompletion(day, 'e');

        QueryWrapper<AlarmCar> alarmCarQueryWrapper = new QueryWrapper<>();
        alarmCarQueryWrapper.lambda().ge(AlarmCar::getAlarmTime,startTime);
        alarmCarQueryWrapper.lambda().le(AlarmCar::getAlarmTime,endTime);
        List<AlarmCar> alarmCars = alarmCarMapper.selectList(alarmCarQueryWrapper);

        //车报警
        Map<String, Long> alarmCarMap = alarmCars.stream().collect(Collectors.groupingBy(AlarmCar::getAlarmTypeName, Collectors.counting()));

        Map<String,Long> carAlarmMap = new HashMap();
        carAlarmMap.put("超速",0L);
        carAlarmMap.put("漏油",0L);
        carAlarmMap.put("离线",0L);
        alarmCarMap.keySet().forEach(t->{
            if ("超速".equals(t)){
                carAlarmMap.put("超速",Long.parseLong(String.valueOf(alarmCarMap.get(t))));
            } else if ("漏油".equals(t)){
                carAlarmMap.put("漏油",Long.parseLong(String.valueOf(alarmCarMap.get(t))));
            } else if ("离线".equals(t)){
                carAlarmMap.put("离线",Long.parseLong(String.valueOf(alarmCarMap.get(t))));
            }
        });

        // 转list
        List<Map.Entry<String,Long>> carAlarmList = new ArrayList<>(carAlarmMap.entrySet());
        carAlarmList.sort(Comparator.comparing(Map.Entry::getValue));
        //排序
        Collections.sort(carAlarmList, (o1, o2) -> {
            Long d1 = o1.getValue();
            Long d2 = o2.getValue();
            return d2.compareTo(d1);
        });

        //格式化list
        List<String> alarmCarList = new ArrayList<>();
        carAlarmList.forEach(t->{
            alarmCarList.add(t.getKey() + ":" + t.getValue());
        });

        result.put("carAlarmNum", alarmCars.size());
        result.put("carAlarmList", alarmCarList);

        QueryWrapper<CarViolation> carViolationQueryWrapper = new QueryWrapper<>();
        carViolationQueryWrapper.lambda().ge(CarViolation::getTime,startTime);
        carViolationQueryWrapper.lambda().le(CarViolation::getTime,endTime);
        List<CarViolation> carViolations = carViolationMapper.selectList(carViolationQueryWrapper);

        //车的违规
        Map<String, Long> violationCarMap = carViolations.stream().collect(Collectors.groupingBy(CarViolation::getRuleTypeName, Collectors.counting()));
        Map<String, Long> carViolationMap = new HashMap();
        carViolationMap.put("速度限制",0L);
        carViolationMap.put("车辆停留",0L);
        carViolationMap.put("车辆空驶",0L);
        violationCarMap.keySet().forEach(t->{
            if ("速度限制".equals(t)){
                carViolationMap.put("速度限制",Long.parseLong(String.valueOf(violationCarMap.get(t))));
            } else if ("车辆停留".equals(t)){
                carViolationMap.put("车辆停留",Long.parseLong(String.valueOf(violationCarMap.get(t))));
            } else if ("车辆空驶".equals(t)){
                carViolationMap.put("车辆空驶",Long.parseLong(String.valueOf(violationCarMap.get(t))));
            }
        });

        // 转list
        List<Map.Entry<String,Long>> carViolationList = new ArrayList<>(carViolationMap.entrySet());
        carViolationList.sort(Comparator.comparing(Map.Entry::getValue));
        //排序
        Collections.sort(carViolationList, (o1, o2) -> {
            Long d1 = o1.getValue();
            Long d2 = o2.getValue();
            return d2.compareTo(d1);
        });

        //格式化list
        List<String> violationCarList = new ArrayList<>();
        carViolationList.forEach(t->{
            violationCarList.add(t.getKey() + ":" + t.getValue());
        });

        result.put("carViolationNum", carViolations.size());
        result.put("carViolationList", violationCarList);

        return result;
    }

    @Override
    public void deal(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("alarmCarIds"))) {
            throw new HssException("参数错误");
        }
        String alarmCarIdStr = params.getString("alarmCarIds");
        String[] alarmCarIds = alarmCarIdStr.split(",");
        QueryWrapper<AlarmCar> alarmCarQueryWrapper = new QueryWrapper<>();
        alarmCarQueryWrapper.lambda().in(AlarmCar::getAlarmCarId, alarmCarIds);
        List<AlarmCar> alarmCarList = alarmCarMapper.selectList(alarmCarQueryWrapper);
        User user = userMapper.selectById(uid);
        Map<String, AlarmCar> alarmCarMap = null;
        if (!alarmCarList.isEmpty()) {
            alarmCarMap = GroupingByUtils.getGroupingForMapEntity(alarmCarList, AlarmCar::getAlarmCarId
                    , Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));

        } else {
            alarmCarMap = new HashMap<>();
        }

        List<AlarmCar> alarmCars = new ArrayList<>();
        AlarmCar aalarmCar = null;
        AlarmHandleLog alarmHandleLog = null;
        List<AlarmHandleLog> alarmHandleLogList = new LinkedList<>();
        for (String alarmCarId : alarmCarIds) {
            AlarmCar alarmCar = new AlarmCar(alarmCarId, params.getString("dealType"), params.getString("dealRemark"), uid);
            alarmCars.add(alarmCar);
            if (alarmCarMap.containsKey(alarmCarId)) {
                aalarmCar = alarmCarMap.get(alarmCarId);
                alarmHandleLog = getAlarmHandleLog(aalarmCar, params, uid, user);
                alarmHandleLogList.add(alarmHandleLog);
            }

        }
        alarmHandleLogService.saveBatch(alarmHandleLogList);
        updateBatchById(alarmCars);
    }

    private AlarmHandleLog getAlarmHandleLog(AlarmCar alarmCar, JSONObject params, String uid, User user) {
        AlarmHandleLog alarmHandleLog = new AlarmHandleLog(StringUtils.uuid(), alarmCar.getAlarmCarId(), alarmCar.getCarId(), alarmCar.getCarName(), alarmCar.getCarTypeId(), alarmCar.getCarTypeName(),
                new Date(), alarmCar.getDepId(), alarmCar.getDepName(), alarmCar.getAlarmTypeId(), alarmCar.getAlarmTypeName(), params.getString("dealType"), uid, user != null ? user.getName() : "",
                params.getString("dealRemark"), alarmCar.getContent(), alarmCar.getAlarmStartTime(), alarmCar.getAlarmEndTime(), alarmCar.getIsKeep(), alarmCar.getLng(), alarmCar.getLat(),
                alarmCar.getAlarmTime(), alarmCar.getAddress(), "0", "car"

        );
        return alarmHandleLog;
    }

    @Override
    public JSONObject getCarPolice(JSONObject params) {
        JSONObject json = new JSONObject();
        QueryWrapper<AlarmCar> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("alarm_type_name");
        queryWrapper.select("alarm_type_name");
        if (params != null) {
            if (StringUtils.isNotEmpty(params.getString("type")) && params.getString("type") != null) {
                queryWrapper.lambda().eq(AlarmCar::getAlarmTypeId, params.getString("type"));
            }
            if (StringUtils.isNotEmpty(params.getString("beginTime")) && params.getString("beginTime") != null && StringUtils.isNotEmpty(params.getString("endTime")) && params.getString("endTime") != null) {
                queryWrapper.lambda().between(AlarmCar::getCreateTime, params.getString("beginTime"), params.getString("endTime"));
            }
        }
        queryWrapper.lambda().groupBy(AlarmCar::getAlarmTypeName);
        List<Object> legendData = this.listObjs(queryWrapper);
        json.put("legendData", legendData);

        QueryWrapper<AlarmCar> queryWrapperx = new QueryWrapper<>();
        queryWrapperx.isNotNull("car_name");
        queryWrapperx.select("car_name");
        if (params != null) {
            if (StringUtils.isNotEmpty(params.getString("persionId")) && params.getString("persionId") != null) {
                queryWrapperx.lambda().eq(AlarmCar::getCarId, params.getString("persionId"));
            }
            if (StringUtils.isNotEmpty(params.getString("beginTime")) && params.getString("beginTime") != null && StringUtils.isNotEmpty(params.getString("endTime")) && params.getString("endTime") != null) {
                queryWrapperx.lambda().between(AlarmCar::getCreateTime, params.getString("beginTime"), params.getString("endTime"));
            }
        }
        queryWrapperx.lambda().groupBy(AlarmCar::getCarName);
        List<Object> xAxisData = this.listObjs(queryWrapperx);
        json.put("xAxisData", xAxisData);

        QueryWrapper<AlarmCar> queryWrappers = new QueryWrapper<>();
        queryWrappers.select("person_name as xAxisData,alarm_type_name as legendData,count(1) as data");
        if (params != null) {
            if (StringUtils.isNotEmpty(params.getString("type")) && params.getString("type") != null) {
                queryWrappers.lambda().eq(AlarmCar::getAlarmTypeId, params.getString("type"));
            }
            if (StringUtils.isNotEmpty(params.getString("persionId")) && params.getString("persionId") != null) {
                queryWrappers.lambda().eq(AlarmCar::getCarId, params.getString("persionId"));
            }
            if (StringUtils.isNotEmpty(params.getString("beginTime")) && params.getString("beginTime") != null && StringUtils.isNotEmpty(params.getString("endTime")) && params.getString("endTime") != null) {
                queryWrappers.lambda().between(AlarmCar::getCreateTime, params.getString("beginTime"), params.getString("endTime"));
            }
        }
        queryWrappers.lambda().groupBy(AlarmCar::getCarId, AlarmCar::getAlarmTypeName);
        List<Map<String, Object>> alarms = this.listMaps(queryWrappers);
        List<Map<String, List>> seriesData = new ArrayList<Map<String, List>>();
        if (!legendData.isEmpty() && legendData != null) {
            for (Object legendDatas : legendData) {
                List list = new ArrayList();
                for (Map<String, Object> alarm : alarms) {
                    if (alarm.get("legendData") != null) {
                        if (alarm.get("legendData").equals(legendDatas)) {
                            list.add(alarm.get("data"));
                        } else {
                            if (!this.iset(alarms, legendDatas, alarm.get("xAxisData"))) {
                                list.add(0);
                            }
                        }
                    }
                }
                Map<String, List> map = new HashMap<String, List>();
                map.put(legendDatas.toString(), list);
                seriesData.add(map);
            }
        }
        json.put("seriesData", seriesData);
        return json;
    }

    private boolean iset(List<Map<String, Object>> alarms, Object legendData, Object xAxisData) {
        for (Map<String, Object> alarm : alarms) {
            if (alarm.get("legendData") != null && alarm.get("xAxisData") != null) {
                if (alarm.get("legendData").equals(legendData) && alarm.get("xAxisData").equals(xAxisData)) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public JSONObject collectList(JSONObject params) throws HssException {
        JSONObject res = new JSONObject();
        Long page = (StringUtils.isEmpty(params.getLong("page")) || params.getLong("page") == 0) ? 1 : params.getLong("page");
        Long size = (StringUtils.isEmpty(params.getLong("size")) || params.getLong("size") == 0) ? 10 : params.getLong("size");
        params.put("offset", (page - 1) * size);
        params.put("limit", size);
        List<Map<String, Object>> list = alarmCarMapper.collectList(params);
        long count = alarmCarMapper.collectListCount(params);
        res.put("list", list);
        res.put("total", count);
        res.put("current", page);
        res.put("pages", (int) Math.ceil(count / size));
        res.put("size", list.size());
        return res;
    }



    @Override
    public List<AlarmCarCharts> selectAlarmCarForTable(AlarmCar alarmCar) {
        if (Objects.isNull(alarmCar.getAlarmStartTime())){
            alarmCar.setAlarmStartTime(DateUtil.parseDateTime(DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN)+"-01 00:00:00"));
        } else {
            alarmCar.setAlarmStartTime(DateUtil.parseDateTime(DateUtil.formatDate(alarmCar.getAlarmStartTime()) +" 00:00:00"));
        }
        if (Objects.isNull(alarmCar.getAlarmEndTime())){
            alarmCar.setAlarmEndTime(DateUtil.parseDateTime(DateUtil.formatDate(new Date())+" 23:59:59"));
        } else {
            alarmCar.setAlarmEndTime(DateUtil.parseDateTime(DateUtil.formatDate(alarmCar.getAlarmEndTime())+" 23:59:59"));
        }
        if(StringUtils.isNotEmpty(alarmCar.getDepId())){
            List<String> depIds=departService.getChildIdsByIId(alarmCar.getDepId());
            alarmCar.setDepIds(depIds);
        }
        List<AlarmCarCharts> alarmCarChartsList = alarmCarMapper.selectAlarmCarForTable(alarmCar);
        if (Objects.nonNull(alarmCarChartsList) && alarmCarChartsList.size()>0){
            QueryWrapper<AlarmCar> alarmCarQueryWrapper=new QueryWrapper<>();
            if (StringUtils.isNotEmpty(alarmCar.getCarName())){
                alarmCarQueryWrapper.lambda().eq(AlarmCar::getCarName,alarmCar.getCarName());
            }
            if (StringUtils.isNotEmpty(alarmCar.getAlarmTypeName())){
                alarmCarQueryWrapper.lambda().eq(AlarmCar::getAlarmTypeName,alarmCar.getAlarmTypeName());
            }
            if (CollectionUtils.isNotEmpty(alarmCar.getCarNames())){
                alarmCarQueryWrapper.lambda().in(AlarmCar::getCarName,alarmCar.getCarNames());
            }
            alarmCarQueryWrapper.lambda().ge(AlarmCar::getAlarmTime,alarmCar.getAlarmStartTime());
            alarmCarQueryWrapper.lambda().le(AlarmCar::getAlarmTime,alarmCar.getAlarmEndTime());

            List<AlarmCar> alarmCarList = alarmCarMapper.selectList(alarmCarQueryWrapper);

            alarmCarList.forEach(t->{
                t.setAlarmDate(DateUtil.formatDate(t.getAlarmTime()));
            });
            Map<String, List<AlarmCar>> alarmCarMap = alarmCarList.stream().collect(Collectors.groupingBy(AlarmCar::getCarName));

            Map<String, Map<String, List<AlarmCar>>> map2 = new HashMap<>();
            alarmCarMap.keySet().forEach(t->{
                List<AlarmCar> alarmCars = alarmCarMap.get(t);
                Map<String, List<AlarmCar>> alarmTypeCarMap = alarmCars.stream().collect(Collectors.groupingBy(AlarmCar::getAlarmTypeName));
                map2.put(alarmCars.get(0).getCarName(),alarmTypeCarMap);
            });

            for (AlarmCarCharts alarmCarCharts:alarmCarChartsList
            ) {
                if (Objects.nonNull(map2.get(alarmCarCharts.getCarName()).get("离线"))){
                    alarmCarCharts.setLxCount(map2.get(alarmCarCharts.getCarName()).get("离线").size());
                }
                if (Objects.nonNull(map2.get(alarmCarCharts.getCarName()).get("漏油"))){
                    alarmCarCharts.setLyCount(map2.get(alarmCarCharts.getCarName()).get("漏油").size());
                }
                if (Objects.nonNull(map2.get(alarmCarCharts.getCarName()).get("超速"))){
                    alarmCarCharts.setCsCount(map2.get(alarmCarCharts.getCarName()).get("超速").size());
                }
            }
        }
        return alarmCarChartsList;
    }

    @Override
    public List<List<Object>> selectAlarmCarForCharts(AlarmCar alarmCar) throws ParseException {
        if (Objects.isNull(alarmCar.getAlarmStartTime())){
            alarmCar.setAlarmStartTime(DateUtil.parseDateTime(DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN)+"-01 00:00:00"));
        } else {
            alarmCar.setAlarmStartTime(DateUtil.parseDateTime(DateUtil.formatDate(alarmCar.getAlarmStartTime()) +" 00:00:00"));
        }
        if (Objects.isNull(alarmCar.getAlarmEndTime())){
            alarmCar.setAlarmEndTime(DateUtil.parseDateTime(DateUtil.formatDate(new Date())+" 23:59:59"));
        } else {
            alarmCar.setAlarmEndTime(DateUtil.parseDateTime(DateUtil.formatDate(alarmCar.getAlarmEndTime())+" 23:59:59"));
        }
        if(StringUtils.isNotEmpty(alarmCar.getDepId())){
            List<String> depIds=departService.getChildIdsByIId(alarmCar.getDepId());
            alarmCar.setDepIds(depIds);
        }
        Date startDate = alarmCar.getAlarmStartTime();
        Date endDate = alarmCar.getAlarmEndTime();
        List<AlarmCarCharts> bTableList = alarmCarMapper.selectAlarmCarForCharts(alarmCar);

        if (Objects.nonNull(bTableList) && bTableList.size()>0){
            QueryWrapper<AlarmCar> alarmCarQueryWrapper=new QueryWrapper<>();
            if (StringUtils.isNotEmpty(alarmCar.getCarName())){
                alarmCarQueryWrapper.lambda().eq(AlarmCar::getCarName,alarmCar.getCarName());
            }
            if (StringUtils.isNotEmpty(alarmCar.getAlarmTypeName())){
                alarmCarQueryWrapper.lambda().eq(AlarmCar::getAlarmTypeName,alarmCar.getAlarmTypeName());
            }
            if ("2".equals(alarmCar.getDateType())){
                alarmCarQueryWrapper.lambda().ge(AlarmCar::getAlarmTime,bTableList.get(0).getAlarmTime() + "-01 00:00:00");
                alarmCarQueryWrapper.lambda().le(AlarmCar::getAlarmTime,bTableList.get(bTableList.size()-1).getAlarmTime() + "-31 23:59:59");
            } else {
                alarmCarQueryWrapper.lambda().ge(AlarmCar::getAlarmTime,bTableList.get(0).getAlarmTime() + " 00:00:00");
                alarmCarQueryWrapper.lambda().le(AlarmCar::getAlarmTime,bTableList.get(bTableList.size()-1).getAlarmTime() + " 23:59:59");
            }

            List<AlarmCar> alarmCarList = alarmCarMapper.selectList(alarmCarQueryWrapper);

            if ("2".equals(alarmCar.getDateType())){
                alarmCarList.forEach(t->{
                    t.setAlarmDate(DateUtil.format(t.getAlarmTime(),DatePattern.NORM_MONTH_PATTERN));
                });
            } else {
                alarmCarList.forEach(t->{
                    t.setAlarmDate(DateUtil.formatDate(t.getAlarmTime()));
                });
            }

            Map<String, List<AlarmCar>> alarmCarMap = alarmCarList.stream().collect(Collectors.groupingBy(AlarmCar::getAlarmDate));

            Map<String, Map<String, List<AlarmCar>>> map2 = new HashMap<>();
            alarmCarMap.keySet().forEach(t->{
                List<AlarmCar> alarmCars = alarmCarMap.get(t);
                Map<String, List<AlarmCar>> alarmTypeCarMap = alarmCars.stream().collect(Collectors.groupingBy(AlarmCar::getAlarmTypeName));
                map2.put(alarmCars.get(0).getAlarmDate(),alarmTypeCarMap);
            });

            for (AlarmCarCharts alarmCarCharts:bTableList
            ) {
                if (Objects.nonNull(map2) && map2.size() > 0){
                    if (Objects.nonNull(map2.get(alarmCarCharts.getAlarmTime()).get("离线"))){
                        alarmCarCharts.setLxCount(map2.get(alarmCarCharts.getAlarmTime()).get("离线").size());
                    }
                    if (Objects.nonNull(map2.get(alarmCarCharts.getAlarmTime()).get("漏油"))){
                        alarmCarCharts.setLyCount(map2.get(alarmCarCharts.getAlarmTime()).get("漏油").size());
                    }
                    if (Objects.nonNull(map2.get(alarmCarCharts.getAlarmTime()).get("超速"))){
                        alarmCarCharts.setCsCount(map2.get(alarmCarCharts.getAlarmTime()).get("超速").size());
                    }
                }
            }
        }
        if ("2".equals(alarmCar.getDateType())){
            return getSelectAlarmForChartsByMonth(startDate, endDate, bTableList);
        } else {
            return getSelectAlarmForCharts(startDate, endDate, bTableList);
        }
    }

    private  List<List<Object>> getSelectAlarmForCharts(Date startDate,Date endDate,List<AlarmCarCharts> bTableList) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<Object> resList = new ArrayList<>();
        List<List<Object>> resList2 = new ArrayList<>();
        List<String> dateStringList = new ArrayList<>();
        dateStringList = Tools.getDateList(format, startDate, endDate);
        Boolean flag = true;
        for (int i = 0; i < dateStringList.size(); i++) {
            resList.add(dateStringList.get(i));
            for (AlarmCarCharts c : bTableList) {
                if (dateStringList.get(i).equals(c.getAlarmTime())) {
                    flag = false;
                    resList.addAll(c.getResList());
                    resList2.add(resList);
                }
            }
            for (AlarmCarCharts c : bTableList) {
                if (flag) {
                    resList.add(0);
                    resList.add(0);
                    resList.add(0);
                    resList.add(0);
                    resList2.add(resList);
                    flag = false;
                }
            }

            resList = new ArrayList<>();
            flag = true;

        }
        return resList2;
    }
    private  List<List<Object>> getSelectAlarmForChartsByMonth(Date startDate,Date endDate,List<AlarmCarCharts> bTableList) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        List<Object> resList = new ArrayList<>();
        List<List<Object>> resList2 = new ArrayList<>();
        List<String> dateStringList = new ArrayList<>();

        String beginDate =  DateUtil.formatDate(startDate);
        String lastDate = DateUtil.formatDate(endDate);
        dateStringList = Tools.getMonthList(beginDate, lastDate);
        Boolean flag = true;
        for (int i = 0; i < dateStringList.size(); i++) {
            resList.add(dateStringList.get(i));
            for (AlarmCarCharts c : bTableList) {
                if (dateStringList.get(i).equals(c.getAlarmTime())) {
                    flag = false;
                    resList.addAll(c.getResList());
                    resList2.add(resList);
                }
            }
            for (AlarmCarCharts c : bTableList) {
                if (flag) {
                    resList.add(0);
                    resList.add(0);
                    resList.add(0);
                    resList.add(0);
                    resList2.add(resList);
                    flag = false;
                }
            }

            resList = new ArrayList<>();
            flag = true;

        }
        return resList2;
    }

    /**
     * 列表明细
     */
    @Override
    public TableDataInfo selectAlarmCarForTableDetail(AlarmCar alarmCar) {
        if (Objects.isNull(alarmCar.getAlarmStartTime())){
            alarmCar.setAlarmStartTime(DateUtil.parseDateTime(DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN)+"-01 00:00:00"));
        } else {
            alarmCar.setAlarmStartTime(DateUtil.parseDateTime(DateUtil.formatDate(alarmCar.getAlarmStartTime()) +" 00:00:00"));
        }
        if (Objects.isNull(alarmCar.getAlarmEndTime())){
            alarmCar.setAlarmEndTime(DateUtil.parseDateTime(DateUtil.formatDate(new Date())+" 23:59:59"));
        } else {
            alarmCar.setAlarmEndTime(DateUtil.parseDateTime(DateUtil.formatDate(alarmCar.getAlarmEndTime())+" 23:59:59"));
        }
        QueryWrapper<AlarmCar> alarmCarQueryWrapper=new QueryWrapper<>();
        if (StringUtils.isNotEmpty(alarmCar.getDepId())) {
            List<String> depIds=departService.getChildIdsByIId(alarmCar.getDepId());
            alarmCarQueryWrapper.lambda().in(AlarmCar::getDepId, depIds);
        }
        if (StringUtils.isNotEmpty(alarmCar.getCarId())){
            alarmCarQueryWrapper.lambda().eq(AlarmCar::getCarId,alarmCar.getCarId());
        }
        if (StringUtils.isNotEmpty(alarmCar.getCarName())){
            alarmCarQueryWrapper.lambda().eq(AlarmCar::getCarName,alarmCar.getCarName());
        }
        if (StringUtils.isNotEmpty(alarmCar.getAlarmTypeName())){
            alarmCarQueryWrapper.lambda().eq(AlarmCar::getAlarmTypeName,alarmCar.getAlarmTypeName());
        }
        alarmCarQueryWrapper.lambda().eq(AlarmCar::getCarId,alarmCar.getCarId());
        alarmCarQueryWrapper.lambda().ge(AlarmCar::getAlarmTime,alarmCar.getAlarmStartTime());
        alarmCarQueryWrapper.lambda().le(AlarmCar::getAlarmTime,alarmCar.getAlarmEndTime());
        alarmCarQueryWrapper.lambda().orderByDesc(AlarmCar::getAlarmTime);

        List<AlarmCar> alarmCarList = alarmCarMapper.selectList(alarmCarQueryWrapper);

        List<AlarmCarTableDetailVO> alarmCarTableDetailVOList = new ArrayList<>();
        alarmCarList.forEach(t -> {
            AlarmCarTableDetailVO alarmCarTableDetailVO = new AlarmCarTableDetailVO();
            alarmCarTableDetailVO.setCarId(t.getCarId());
            alarmCarTableDetailVO.setCarName(t.getCarName());
            alarmCarTableDetailVO.setCarTypeName(t.getCarTypeName());
            alarmCarTableDetailVO.setDepName(t.getDepName());
            alarmCarTableDetailVO.setAlarmTypeName(t.getAlarmTypeName());
            alarmCarTableDetailVO.setAlarmStartTime(DateUtil.formatDateTime(t.getAlarmStartTime()));
            alarmCarTableDetailVO.setAlarmEndTime(DateUtil.formatDateTime(t.getAlarmEndTime()));
            alarmCarTableDetailVO.setContent(t.getContent());
            /** 保存地址 **/
            String currentAddress = locationUtil.getAddress(t.getLng(), t.getLat());
            if (StringUtils.isNotEmpty(currentAddress)) {
                alarmCarTableDetailVO.setAddress(currentAddress);
            } else {
                alarmCarTableDetailVO.setAddress("");
            }
            alarmCarTableDetailVOList.add(alarmCarTableDetailVO);
        });
        return Tools.buildTableDataInfo(alarmCar.getPageNum(), alarmCar.getPageSize(), alarmCarTableDetailVOList);
    }

    /**
     * 列表明细导出
     */
    @Override
    public List<AlarmCarTableDetailVO> selectAlarmCarForExcelDetail(AlarmCar alarmCar) {
        if (Objects.isNull(alarmCar.getAlarmStartTime())){
            alarmCar.setAlarmStartTime(DateUtil.parseDateTime(DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN)+"-01 00:00:00"));
        } else {
            alarmCar.setAlarmStartTime(DateUtil.parseDateTime(DateUtil.formatDate(alarmCar.getAlarmStartTime()) +" 00:00:00"));
        }
        if (Objects.isNull(alarmCar.getAlarmEndTime())){
            alarmCar.setAlarmEndTime(DateUtil.parseDateTime(DateUtil.formatDate(new Date())+" 23:59:59"));
        } else {
            alarmCar.setAlarmEndTime(DateUtil.parseDateTime(DateUtil.formatDate(alarmCar.getAlarmEndTime())+" 23:59:59"));
        }
        QueryWrapper<AlarmCar> alarmCarQueryWrapper=new QueryWrapper<>();
        if (StringUtils.isNotEmpty(alarmCar.getCarId())){
            alarmCarQueryWrapper.lambda().eq(AlarmCar::getCarId,alarmCar.getCarId());
        }
        if (StringUtils.isNotEmpty(alarmCar.getCarName())){
            alarmCarQueryWrapper.lambda().eq(AlarmCar::getCarName,alarmCar.getCarName());
        }
        if (StringUtils.isNotEmpty(alarmCar.getAlarmTypeName())){
            alarmCarQueryWrapper.lambda().eq(AlarmCar::getAlarmTypeName,alarmCar.getAlarmTypeName());
        }
        alarmCarQueryWrapper.lambda().eq(AlarmCar::getCarId,alarmCar.getCarId());
        alarmCarQueryWrapper.lambda().ge(AlarmCar::getAlarmTime,alarmCar.getAlarmStartTime());
        alarmCarQueryWrapper.lambda().le(AlarmCar::getAlarmTime,alarmCar.getAlarmEndTime());
        alarmCarQueryWrapper.lambda().orderByDesc(AlarmCar::getAlarmTime);

        List<AlarmCar> alarmCarList = alarmCarMapper.selectList(alarmCarQueryWrapper);
        //获取明细日期
        if (CollectionUtils.isNotEmpty(alarmCar.getAlarmTimes())) {
            Predicate<AlarmCar> inTime = x -> (alarmCar.getAlarmTimes().contains(Tools.getDayString(x.getAlarmStartTime()).concat(",").concat(Tools.getDayString(x.getAlarmEndTime()))));
            alarmCarList = alarmCarList.stream().filter(inTime).collect(Collectors.toList());
        }

        List<AlarmCarTableDetailVO> alarmCarTableDetailVOList = new ArrayList<>();
        alarmCarList.forEach(t -> {
            AlarmCarTableDetailVO alarmCarTableDetailVO = new AlarmCarTableDetailVO();
            alarmCarTableDetailVO.setCarId(t.getCarId());
            alarmCarTableDetailVO.setCarName(t.getCarName());
            alarmCarTableDetailVO.setCarTypeName(t.getCarTypeName());
            alarmCarTableDetailVO.setDepName(t.getDepName());
            alarmCarTableDetailVO.setAlarmTypeName(t.getAlarmTypeName());
            alarmCarTableDetailVO.setAlarmStartTime(DateUtil.formatDateTime(t.getAlarmStartTime()));
            alarmCarTableDetailVO.setAlarmEndTime(DateUtil.formatDateTime(t.getAlarmEndTime()));
            alarmCarTableDetailVO.setContent(t.getContent());
            /** 保存地址 **/
            String currentAddress = locationUtil.getAddress(t.getLng(), t.getLat());
            if (StringUtils.isNotEmpty(currentAddress)) {
                alarmCarTableDetailVO.setAddress(currentAddress);
            } else {
                alarmCarTableDetailVO.setAddress("");
            }
            alarmCarTableDetailVOList.add(alarmCarTableDetailVO);
        });
        return alarmCarTableDetailVOList;
    }
}
